
#include "member_BHBoxLayout.h"

using namespace BWE;

member_BHBoxLayout::member_BHBoxLayout(BHBoxLayout* layout)
{
	boss = layout;
	parent = 0;
}
member_BHBoxLayout::~member_BHBoxLayout()
{

}

int member_BHBoxLayout::distributeWidth(int remainWidth)
{
	int visualCount = 0;
	for (int i = 0; i < items.size(); i++)
	{
		LayoutItem& item = items[i];
		visualCount += item.prepare(remainWidth) ? 1 : 0;
	}
	if (visualCount < 1)
		return remainWidth;

	while (remainWidth != 0)
	{
		float totalStretch = 0;
		for (int i = 0; i < items.size(); i++)
		{
			if (items[i].finishWidth)
				continue;
			totalStretch += items[i].sizeStretch().widthStretch();
		}
		if (totalStretch < 0.00001)
			break;

		int used = 0;
		for (int i = 0; i < items.size(); i++)
		{
			LayoutItem& item = items[i];

			if (item.finishWidth)
				continue;
			int width = item.sizeStretch().widthStretch() / totalStretch * remainWidth;
			if (width == 0)
				continue;
			int maxWidth = item.maxSize().width();
			int minWidth = item.minSize().width();
			if (width + item.realSize.width() > maxWidth)
			{
				used += maxWidth - item.realSize.width();
				item.realSize.setWidth(maxWidth);
				item.finishWidth = true;
				continue;
			}
			if (width + item.realSize.width() < minWidth)
			{
				used += minWidth - item.realSize.width();
				item.realSize.setWidth(minWidth);
				item.finishWidth = true;
				continue;
			}
			used += width;
			item.realSize += BSize(width, 0);
		}
		if (used == 0)
			break;
		remainWidth -= used;
	}
	while (remainWidth > 0)
	{
		for (int i = 0; i < items.size(); i++)
		{
			if (items[i].ignored())
				continue;
			items[i].realSize.width() += 1;
			remainWidth--;
			if (remainWidth < 1)
				break;
		}
	}
	return remainWidth;
}
